# wzry_cli.py - 命令行接口
"""
王者荣耀查询命令行工具
"""

import requests
import json
import click
import uvicorn
from typing import Optional


class WZRYClient:
    """王者荣耀查询客户端"""
    
    def __init__(self, host: str = "127.0.0.1", port: int = 8000, token: str = ""):
        self.base_url = f"http://{host}:{port}"
        self.headers = {"Authorization": f"Bearer {token}"} if token else {}
    
    def add_device(self, device_id: str) -> dict:
        """添加设备"""
        response = requests.post(
            f"{self.base_url}/devices/add",
            json={"device_id": device_id},
            headers=self.headers
        )
        return response.json()
    
    def remove_device(self, device_id: str) -> dict:
        """移除设备"""
        response = requests.delete(
            f"{self.base_url}/devices/{device_id}",
            headers=self.headers
        )
        return response.json()
    
    def get_device_status(self) -> dict:
        """获取设备状态"""
        response = requests.get(
            f"{self.base_url}/devices/status",
            headers=self.headers
        )
        return response.json()
    
    def search_player(self, player_name: str, timeout: int = 30) -> dict:
        """搜索玩家"""
        response = requests.post(
            f"{self.base_url}/search",
            json={"player_name": player_name, "timeout": timeout},
            headers=self.headers
        )
        return response.json()
    
    def health_check(self) -> dict:
        """健康检查"""
        response = requests.get(f"{self.base_url}/health")
        return response.json()


@click.group()
@click.option('--host', default='127.0.0.1', help='API服务器地址')
@click.option('--port', default=8000, help='API服务器端口')
@click.option('--token', default='wzry_admin_token', help='访问令牌')
@click.pass_context
def cli(ctx, host, port, token):
    """王者荣耀查询命令行工具"""
    ctx.ensure_object(dict)
    ctx.obj['client'] = WZRYClient(host, port, token)


@cli.command()
@click.argument('device_id')
@click.pass_context
def add_device(ctx, device_id):
    """添加设备到连接池"""
    client = ctx.obj['client']
    result = client.add_device(device_id)
    click.echo(json.dumps(result, ensure_ascii=False, indent=2))


@cli.command()
@click.argument('device_id')
@click.pass_context
def remove_device(ctx, device_id):
    """从连接池移除设备"""
    client = ctx.obj['client']
    result = client.remove_device(device_id)
    click.echo(json.dumps(result, ensure_ascii=False, indent=2))


@cli.command()
@click.pass_context
def status(ctx):
    """查看设备状态"""
    client = ctx.obj['client']
    result = client.get_device_status()
    click.echo(json.dumps(result, ensure_ascii=False, indent=2))


@cli.command()
@click.argument('player_name')
@click.option('--timeout', default=30, help='查询超时时间')
@click.pass_context
def search(ctx, player_name, timeout):
    """搜索玩家"""
    client = ctx.obj['client']
    result = client.search_player(player_name, timeout)
    
    if result['success']:
        click.echo(f"🎉 找到 {len(result['data'])} 个结果 (耗时: {result['query_time']:.2f}秒)")
        for i, player in enumerate(result['data'], 1):
            click.echo(f"\n📋 结果 {i}:")
            click.echo(f"  玩家昵称: {player['nickname']}")
            click.echo(f"  角色名称: {player['role_name']}")
            click.echo(f"  所属区服: {player['server_info']}")
            click.echo(f"  当前段位: {player['rank_info']}")
    else:
        click.echo(f"❌ 查询失败: {result['message']}")


@cli.command()
@click.pass_context
def health(ctx):
    """检查服务健康状态"""
    client = ctx.obj['client']
    result = client.health_check()
    click.echo(json.dumps(result, ensure_ascii=False, indent=2))


@cli.command()
@click.option('--host', default='127.0.0.1', help='绑定地址')
@click.option('--port', default=8000, help='绑定端口')
def server(host, port):
    """启动API服务器"""
    uvicorn.run("wzry_api:app", host=host, port=port, reload=True)


if __name__ == '__main__':
    cli()